﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace Temperature
{

    class Program
    {
        static void Main(string[] args)
        {
            string CfgPath = string.Format("{0}\\AppConfig.txt", Environment.CurrentDirectory);
            if (!System.IO.File.Exists(CfgPath))
            {
                System.IO.File.AppendAllText(CfgPath, string.Format("{0}\r\nCOM3\r\n{1}", 9600,60));
            }
            string[] strConfig = System.IO.File.ReadAllLines(CfgPath);
            System.IO.Ports.SerialPort sPort = new System.IO.Ports.SerialPort();
            sPort.BaudRate = int.Parse(strConfig[0]);
            sPort.PortName = strConfig[1];
            int iSleep = 1000*int.Parse(strConfig[2]);
            while (true)
            {
                try
                {
                    sPort.Open();
                    string[] strArr = sPort.ReadLine().Split('=');
                    string strTmp = string.Format("{0},\t{1},\n", DateTime.Now, double.Parse(strArr[1]));
                    Console.WriteLine(strTmp);
                    System.IO.File.AppendAllText(string.Format("{0}\\{1}.Temperature", Environment.CurrentDirectory, DateTime.Now.ToString("yyyyMMdd")), strTmp);
                    sPort.Close();
                    System.Threading.Thread.Sleep(iSleep);
                }
                catch (Exception ex)
                {
                    System.IO.File.AppendAllText(string.Format("{0}\\{1}.log", Environment.CurrentDirectory, DateTime.Now.ToString("yyyyMMdd")), string.Format("{0}\t{1}\r\n", DateTime.Now, ex.Message));
                    if (ex.Message.Equals(string.Format("端口“{0}”不存在。", sPort.PortName)))
                    {
                        Console.WriteLine(ex.Message);
                        break;
                    }
                }
            }
            Console.ReadKey();
        }
    }
}
